package cn.web.base.velocity;

import cn.commons.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Params {

    /**
     * 获取路径参数
     *
     * @param name
     * @return
     */
    public String get(String name) {
        if (StringUtils.isNotBlank(name)) {
            Pattern p = Pattern.compile("(?:^|\\?|&)" + name + "=([^&]*)(?:&|$)");
            Matcher m = p.matcher(getRequest().getQueryString());
            if (m.find()) {
                return m.group(1);
            }
        }
        return null;
    }


    private HttpServletRequest getServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    private HttpServletRequest getRequest() {
        return getServletRequest();
    }

}
